package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.web.dto.BrandVO;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import com.ugoodtech.mdcc.web.dto.ServerResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "品牌")
@RequestMapping("/brand")
@RestController
public class BrandController extends BaseController {

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;


    @ApiOperation("获取品牌")
    @RequestMapping(value = "getAllBrand", method = RequestMethod.GET)
    public JsonResponse getAllBrand(@ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId) {
        if (departmentId == null || departmentId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "参数错误");
        }
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.enabled.eq(true));
        builder.and(qDepartment.id.eq(departmentId));
        Department department = departmentRepository.findOne(builder);
        if (department == null) {
            return JsonResponse.successResponseWithData(new String[0]);
        }
        if (department.getParent() == null) {
            List<Brand> brandList = (List<Brand>) brandRepository.findAll();
            String[] brandArray = new String[brandList.size()];
            for (int i = 0; i < brandList.size(); i++) {
                brandArray[i] = brandList.get(i).getBrandName();
            }
            return JsonResponse.successResponseWithData(brandArray);
        }
//        List<Brand> brandList = department.getBrandList();
//        String[] brandArray = new String[brandList.size()];
//        for (int i = 0; i < brandList.size(); i++) {
//            brandArray[i] = brandList.get(i).getBrandName();
//        }
        return JsonResponse.successResponseWithData("");
    }

    @ApiOperation("获取品牌")
    @RequestMapping(value = "getBrand", method = RequestMethod.GET)
    public JsonResponse getBrand() {
        List<Brand> brandList = (List<Brand>) brandRepository.findAll();
        String[] brandArray = new String[brandList.size() + 1];
        for (int i = 0; i < brandList.size(); i++) {
            brandArray[i] = brandList.get(i).getBrandName();
        }
        brandArray[brandList.size()] = "其他品牌";
        return JsonResponse.successResponseWithData(brandArray);
    }

    @ApiOperation("添加品牌")
    @RequestMapping(value = "addBrand", method = RequestMethod.GET)
    public JsonResponse addBrand(String brandName) {
        if (StringUtils.isEmpty(brandName)) {
            return JsonResponse.errorResponseWithError("抱歉", "请传入数据");
        }
        Brand brand = brandRepository.selectByName(brandName);
        if (brand != null) {
            return JsonResponse.errorResponseWithError("抱歉", "已经有此品牌");
        }
        brand = new Brand();
        brand.setBrandName(brandName);
        brandRepository.save(brand);
        Map<String, Object> data = new HashMap<>();
        data.put("str", brandName);
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_add, LogConstants.operate_module_brand, null, data);
        return JsonResponse.successResponse();
    }

    @ApiOperation("获取品牌")
    @RequestMapping(value = "getAllBrand_Id", method = RequestMethod.GET)
    public JsonResponse getAllBrand_Id() {
        List<Brand> brandList = (List<Brand>) brandRepository.findAll();
        List<LabelValue> labelValues = new ArrayList<>();
        for (Brand brand : brandList) {
            LabelValue labelValue = new LabelValue(brand.getBrandName(), brand.getId() + "");
            labelValues.add(labelValue);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    @ApiOperation("获取品牌")
    @RequestMapping(value = "getMyBrand_Id", method = RequestMethod.GET)
    public JsonResponse getMyBrand_Id(Long loginUserId,
                                      @ApiParam("品牌关键字") @RequestParam(value = "brandName", required = false) String brandName) {
        UserProfile userProfile = userProfileRepository.findByUserId(loginUserId);
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前用户");
        }
//        User user = userProfile.getUser();
//        if (user.getUserType().equals(UserType.dealers)) {
        return getAllBrand_Id();
//        }
//        List<LabelValue> labelValues = new ArrayList<>();
//        List<Brand> brandList = userProfile.getBrandList();
//        for (Brand brand : brandList) {
//            LabelValue labelValue = new LabelValue(brand.getBrandName(), brand.getId() + "");
//            labelValues.add(labelValue);
//        }
//        LabelValue labelValue = new LabelValue("其他品牌", "");
//        labelValues.add(labelValue);
//        return JsonResponse.successResponseWithData(labelValues);
    }

    @ApiOperation("获取全部品牌")
    @RequestMapping(value = "/getAllAnswerBrand", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllAnswerBrand(@ApiParam("品牌关键字") @RequestParam(value = "brandname", required = false) String brandname) {
        QQuestionAnswerOption qQuestionAnswerOption = QQuestionAnswerOption.questionAnswerOption;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qQuestionAnswerOption.deleted.eq(false));
        builder.and(qQuestionAnswerOption.enabled.eq(true));
        builder.and(qQuestionAnswerOption.question.id.eq(8L));
        if (StringUtils.isNotEmpty(brandname)) {
            builder.and(qQuestionAnswerOption.name.like("%" + brandname + "%"));
        }
        Page<QuestionAnswerOption> answerOptionList = questionAnswerOptionRepository.findAll(builder, new PageRequest(0, 1000, new Sort(Sort.Direction.ASC, "idx")));
        List<LabelValue> labelValues = new ArrayList<>();
        for (QuestionAnswerOption answerOption : answerOptionList.getContent()) {
            LabelValue labelValue = new LabelValue(answerOption.getName(), answerOption.getId() + "");
            labelValues.add(labelValue);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    @ApiOperation("获取投诉报告的品牌")
    @RequestMapping(value = "/getComplaintBrand", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getComplaintBrand(@ApiParam("品牌关键字") @RequestParam(value = "brandname", required = false) String brandname) {
        QQuestionAnswerOption qQuestionAnswerOption = QQuestionAnswerOption.questionAnswerOption;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qQuestionAnswerOption.deleted.eq(false));
        builder.and(qQuestionAnswerOption.enabled.eq(true));
        builder.and(qQuestionAnswerOption.question.id.eq(194L));
        if (StringUtils.isNotEmpty(brandname)) {
            builder.and(qQuestionAnswerOption.name.like("%" + brandname + "%"));
        }
        Page<QuestionAnswerOption> answerOptionList = questionAnswerOptionRepository.findAll(builder, new PageRequest(0, 1000, new Sort(Sort.Direction.ASC, "idx")));
        List<LabelValue> labelValues = new ArrayList<>();
        for (QuestionAnswerOption answerOption : answerOptionList.getContent()) {
            LabelValue labelValue = new LabelValue(answerOption.getName(), answerOption.getId() + "");
            labelValues.add(labelValue);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }
    @RequestMapping(value = "/brands", method = RequestMethod.GET)
    public ServerResponse listAllBrands(@RequestParam(required = false, defaultValue = "")String brand) {
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, listAllBrandsVO(brand));
    }

    List<BrandVO> listAllBrandsVO(String brand){
        QBrand qBrand =QBrand.brand;
        BooleanBuilder booleanBuilder =new BooleanBuilder();
        if (StringUtils.isNotEmpty(brand)) {
            booleanBuilder.and(qBrand.brandName.like("%" + brand + "%"));
        }
        List<BrandVO> brandVOS=new ArrayList<>();
        Iterable<Brand> all = brandRepository.findAll(booleanBuilder);
        for (Brand brand1 : all) {
            BrandVO brandVO =new BrandVO();
            brandVO.setBrandId(brand1.getId());
            brandVO.setBrandName(brand1.getBrandName());
            brandVO.setId(brand1.getId());
            brandVOS.add(brandVO);
        }
        return brandVOS;
    }
}
